<?php 
/**
 * This file is part of DomFg.
 * 
 * DomFg is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DomFg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DomFg.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @link http://inditel.ee/
 * @copyright 2007-2009 Inditel Meedia OÜ
 * @author Oliver Leisalu <oliver@inditel.ee>
 */

/**
* @author Oliver Leisalu, Inditel Meedia
* @package DomFg
* @subpackage DataSource
*/
class DomArDataSource extends DomFgDataSource {
	
	public function __construct( DomSqlQuery $source, $perPage = 50 ) {
		$this->source( $source );
		$this->perPage( $perPage );
	}
	
	public function source( DomSqlQuery $value ) {
		$this->source = $value->countFoundRows();
	//	$this->source->countFoundRows();
	}

	public function getTotal() {
		if( $this->source instanceof DomSqlQuery )
			throw new RuntimeException('<strong>DomArDataSource::getTotal()</strong> must be called <strong>AFTER DomArDataSource::getData</strong> is called!');
		return $this->source->foundRows();
	}
	
	public function orderBy( $key, $direction = 'ASC' ) {
		$this->source->orderBy( $key . ' ' . $direction);
	}
	
	public function where( $value ) {
		if( empty($this->searchKeys) === true )
			throw new  RuntimeException('Can\'t set where, there are no searchKeys specified!');
		
		$where = array();
		foreach( $this->searchKeys as $key )
			$where[] = '`'.$key.'` LIKE \'%'.addslashes($value).'%\'';
		$this->source->where( implode(',',$where) );
		
	}
	
	/**
	* @return DomArDataIterator
	*/
	public function getData( $start ) {
		$this->source->limit( (int)$start.','.$this->perPage );
		$this->source = $this->source->commit();
		$this->getTotal();
		return $this->source;
	}
}

?>